package Chat_program_Rasmus;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Scanner;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Server {

	// to display time
	private static SimpleDateFormat sdf;
	
	// list of all the online users
	public static ArrayList<Combi> CurrentUsers = new ArrayList<Combi>();
	public static Scanner INPUT = new Scanner("");
	
	// Database connection
	public static Connection conn = null;
	private static String url = "jdbc:mysql://localhost:3306/"; // url
	private static String dbName = "chat"; // database name
	private static String userName = "root"; // db username
	private static String password = "king1978"; // db password
	private static String driver = "com.mysql.jdbc.Driver"; // driver to use (mysql)
	//---------------------------------------------------------------------------
		
	public static void main(String[] args) throws IOException {
		
		final int PORT = 9876;
		
		sdf = new SimpleDateFormat("HH:mm:ss");
		
		try
		{
			
			
			ServerSocket SERVER = new ServerSocket(PORT);
			System.out.println(sdf.format(new Date())+" : Waiting for clients on port :"+PORT);
			
			while(true){
				
				Socket SOCK = SERVER.accept();
				
				// when the server asccepts a socket connection, the connection will be added to the list, 
				// then later we can iterate through the list & echo chatmessages to all the sockets listed.		
				
				// A message to the server console, when a new client is connected, getting their ip address and their hostname		
				System.out.println(sdf.format(new Date())+" : Client connected from : " + SOCK.getLocalAddress().getHostName());
				
				//adding the user to the list of online users, to display who is online on the screen 				
				AddUserName(SOCK);
				
				// building a chat server return object and pass in the socket
				Server_Return CHAT = new Server_Return(SOCK);
				
				// making a new thread for each socket object
				Thread X = new Thread(CHAT);
				// the thread is then started
				X.start();
				
			}
			
			
			
			
		}
		
		catch(Exception X)
		{
			X.printStackTrace();
			System.out.println(sdf.format(new Date())+" : Failed in connecting to port : "+PORT);
		}
		INPUT.close();
	}
	
	//----------------------------------------------------------------------------
	
	public static void AddUserName(Socket X) throws IOException
	
	{
		// the server gets the Username-input from the users in this INPUT scanner
		INPUT = new Scanner(X.getInputStream());
		
		Combi Username = new Combi(INPUT.nextLine(),X);
		
		// adding the name to the arraylist of users
		CurrentUsers.add(Username);
		
		// looping through the arraylist to display all current users online i a Jlist in all client GUI 
		updateList();
		
	}
	
	//-----------------------------------------------------------------------------
	
	public static void updateList() {
		for(int i = 1; i<= Server.CurrentUsers.size(); i++)
		{
			Socket TEMP_SOCK = (Socket) Server.CurrentUsers.get(i-1).getSock();
			
			String[] names = new String[CurrentUsers.size()];
			
			for (int j = 0; j < CurrentUsers.size(); j++) {
				names[j] = CurrentUsers.get(j).getName();
			}
			// send the message to the output stream 
			PrintWriter OUT;
			try {
				OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
				OUT.println("#?!"+Arrays.toString(names));
				// flush the outputstream, so it will be ready for a new message
				OUT.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	//-----------------------------------------------------------------------------

	/**
	 * * Method to open database connection
	 * */
		
	public static Connection open() {
			
		if (conn == null) {
				
			try 
			{		
				Class.forName(driver).newInstance();
				conn = DriverManager.getConnection(url + dbName, userName,password);
				return conn;
				
			} 
			catch (Exception e) 
			{
					return null;
			}
		} 
			
		else {
			return conn;
			
		}
		
	}

	/**
	* Method to close database connection
	*/
		
	public static void close() {
			
		try 
		{		
			conn.close();
			conn = null;
		} 
		
		catch (SQLException e) 
		{
			e.printStackTrace();
			
		}
	}
}
